﻿using System.Threading;

namespace OmniKits.Core
{
    public abstract class RunJob<T> : IRunJob
        where T : class, ICanStart, ICanWait
    {
        internal volatile T _Job;
        protected T Job => _Job;

        protected abstract T GetJob();

        protected virtual bool Run(bool wait)
        {
            var old = _Job;
            if (old != null)
            {
                old.Start();
                if (wait)
                    old.Wait();
                return false;
            }

            var job = GetJob();
            old = Interlocked.CompareExchange(ref _Job, job, null);
            if (old != null)
            {
                old.Start();
                if (wait)
                    old.Wait();
                return false;
            }

            try
            {
                job.Start();
                if (wait)
                    old.Wait();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, null, job);
                throw;
            }
        }

        public virtual bool Start()
            => Run(false);
        public virtual bool Run()
            => Run(true);

        public virtual bool Wait()
        {
            var job = _Job;
            if (job == null)
                return false;
            return job.Wait();
        }
    }
    public abstract class RunJobCanStop<T> : RunJob<T>, IRunJobCanStop
        where T : class, ICanStart, ICanWait, ICanStop
    {
        public virtual bool Stop()
        {
            var job = _Job;
            if (job == null)
                return false;
            job = Interlocked.Exchange(ref _Job, null);
            if (job == null)
                return false;

            try
            {
                job.Stop();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, job, null);
                throw;
            }
        }
    }
}
